/* eslint-disable react/jsx-no-bind */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback, useEffect, useRef } from 'react';
import { Card, Row, Col, List, Modal, Icon } from 'antd';
import { connect } from 'dva';
import { getLStorage } from '@/utils/utils';
import DataSet from '@antv/data-set';
import { useInViewport } from 'ahooks';
import { isArray } from 'lodash';
import classNames from 'classnames';
import Pies from './Pies';
import Charts from './Charts';
import styles from '../style.less';

const legends = {
  in_num: '入库数',
  out_num: '出库数',
  back_num: '退回数',
  sms_num: '短信数',
  complaintRate: '投诉率（万分比）',
  inStorageRate: '入库通知率（%）',
  outStorageRate: '出库率（%）',
  num: '寄件订单数',
  real_num: '实名订单数',
  new_add: '新增粉丝',
  total: '累计粉丝',
};
const nameMapToState = {
  storagePic: 'storagePic', // 入库品牌统计
  outPic: 'outPic', // 出库品牌统计
  storageSummary: 'canvesList', // 出库统计
  storageRate: 'outStorageRateList', // 出库率统计
  complaintRate: 'complaintRateList', // 投诉率统计
  smsSummary: 'smsSummary', // 短信统计
  orderSummary: 'orderSummary', // 订单统计
  fansSummary: 'fansSummary', // 微信粉丝统计
};
const ds = new DataSet();

const WrapperCharts = props => {
  const {
    title,
    name,
    numType,
    dispatch,
    cols,
    chartType,
    _length,
    chartData,
    fields,
    listData,
    cm_id,
    router,
    loading,
    source,
  } = props;
  const [chartList, setChartList] = useState({});
  const [inView, setInView] = useState(false);

  const ref = useRef();
  const inViewPort = useInViewport(ref);

  useEffect(
    () => {
      inViewPort && setInView(true);
    },
    [inViewPort],
  );

  useEffect(
    () => {
      // 通过监听来自state里面的列表的长度来更新图表中的数据
      const obj = {};
      const dataName = nameMapToState[name];
      const dataList = props[dataName];
      if (chartType === 'chart') {
        obj[dataName] = ds
          .createView()
          .source(dataList)
          .transform({
            type: 'fold',
            fields,
            key: 'city',
            value: 'temperature',
          });
      }
      if (chartType == 'pies') {
        obj[dataName] = props[name];
      }
      setChartList(obj);
    },
    [_length, name, chartType, fields],
  );

  useEffect(
    () => {
      const { unique_id, cm_id: query_cm_id } = router.location.query;
      const real_cm_id = isArray(query_cm_id) ? query_cm_id[0] : query_cm_id;
      const data = getLStorage(unique_id) || getLStorage(real_cm_id);
      if (chartType !== 'overview' && data && inView) {
        getData({
          cm_id,
          unique_id,
          _token: data,
          area_id: '',
          source,
        });
      }
    },
    [chartType, getData, cm_id, router.location.query, inView, source],
  );

  const getData = useCallback(
    (payload = {}) => {
      dispatch({
        type: `list/${name}`,
        payload,
      });
    },
    [name, dispatch],
  );

  const handleQuestionClick = text => {
    if (text) {
      Modal.info({
        centered: true,
        content: text,
        icon: false,
      });
    }
  };

  return (
    <div ref={ref}>
      <Card
        className={classNames(`${styles.card}`, {
          [`${styles.card__overview}`]: chartType == 'overview',
        })}
        style={{ margin: '0 5px 5px 5px' }}
        loading={loading}
      >
        {chartType == 'overview' && (
          <Row justify="space-between">
            {title ? (
              <Col span={24}>
                <p style={{ textAlign: 'center', fontWeight: 'bold' }}>{title}</p>
              </Col>
            ) : null}
            {chartData?.map((val, index) => (
              <Col span={24 / chartData.length} style={{ textAlign: 'center' }} key={index}>
                <Row type="flex" justify="center">
                  <Col span={24} onClick={handleQuestionClick.bind(null, val.question)}>
                    {val.name}
                    {val.question && (
                      <Icon style={{ cursor: 'pointer', marginLeft: 5 }} type="question-circle" />
                    )}
                  </Col>
                  <Col span={24} style={{ wordBreak: 'break-word' }}>
                    {val.value}
                  </Col>
                  {val.sub && (
                    <Col span={24} style={{ fontSize: 12, color: 'red' }}>
                      {val.sub}
                    </Col>
                  )}
                </Row>
              </Col>
            ))}
            {listData && (
              <Col span={24}>
                <List
                  split
                  dataSource={listData}
                  renderItem={item => (
                    <List.Item key={item.city_id}>
                      <Row type="flex" justify="space-between" style={{ width: '100%' }}>
                        <Col>{item.abbr_name}</Col>
                        <Col>{item.num}</Col>
                      </Row>
                    </List.Item>
                  )}
                />
              </Col>
            )}
          </Row>
        )}
        {chartType == 'pies' && (
          <>
            <div style={{ textAlign: 'center', fontWeight: 'bold' }}>{title}</div>
            {chartList[name] && <Pies piesList={chartList[name]} numType={numType} />}
          </>
        )}
        {chartType == 'chart' && (
          <>
            <div style={{ textAlign: 'center', fontWeight: 'bold' }}>{title}</div>
            {chartList[nameMapToState[name]] && (
              <Charts
                title=""
                cols={cols}
                canvesList={chartList[nameMapToState[name]]}
                legends={legends}
              />
            )}
          </>
        )}
      </Card>
    </div>
  );
};

WrapperCharts.defaultProps = {
  title: '',
  name: '', // storagePic,outPic,smsSummary,orderSummary,complaintRate,storageRate, fansSummary
  chartType: 'chart', // chart | pies | overview | rank
  cols: {},
  transform: [],
  numType: 'in_num',
};

export default connect(({ list, loading, router }, { name }) => {
  const listName = nameMapToState[name]; // 与状态管理中的effects名称相对应
  const obj = { router };
  if (listName) {
    // 按需添加对应的redux数据
    obj._length = list[listName].length;
    obj[listName] = list[listName];
    obj.loading = loading.effects[`list/${name}`];
  }
  return obj;
})(React.memo(WrapperCharts));
